package com.epfresh.fragment;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.InputFilter;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;

import com.epfresh.R;
import com.epfresh.activity.CartOrderNewActivity;
import com.epfresh.activity.DetailGoodsActivity;
import com.epfresh.activity.HomeActivity;
import com.epfresh.activity.LoginActivity;
import com.epfresh.activity.OfferListActivity;
import com.epfresh.adapter.CartExpandListAdapter;
import com.epfresh.api.entity.RequestEntityMap;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.CashierInputFilter;
import com.epfresh.api.utils.JsonUtils;
import com.epfresh.api.utils.T;
import com.epfresh.api.utils.VerificationUtils;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.api.widget.ptr.PtrMdFrameLayout;
import com.epfresh.basedialog.CustomDialog;
import com.epfresh.bean.AddCarResponse;
import com.epfresh.bean.CartGood;
import com.epfresh.bean.CartGoods;
import com.epfresh.bean.ContentEntity;
import com.epfresh.bean.OfferMyList;
import com.epfresh.global.BaseFragment;
import com.epfresh.global.CartHelper;
import com.epfresh.global.DataManager;
import com.epfresh.utils.FormatUtil;
import com.epfresh.views.MultiStateView;
import com.epfresh.views.dialog.CarTipsDialog;
import com.epfresh.views.dialog.MsgDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import static android.app.Activity.RESULT_OK;

/**
 * Created by wzh on 16-7-1.
 */
public class CartFragment extends BaseFragment {

    private View vBottom;
    private ImageView ivCheck;

    private TextView tvAll;
    private TextView tvTotal;
    private TextView tvTotalName;
    private TextView tvOtherPrice;
    private TextView tvBtn;

    private TextView tvRight,tvOffer;
    private View vLine;
    private PtrMdFrameLayout frameLayout;

    private MultiStateView msView;

    private ExpandableListView lv;

    private CartExpandListAdapter adapter;
//    private List<String> popupMenuItemList = new ArrayList<>();

    //    private PopupList popupList = new PopupList();
    private List<CartGoods> groupList = new ArrayList<>();
    private PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout ptrFrameLayout, View view, View view1) {
            return PtrDefaultHandler.checkContentCanBePulledDown(ptrFrameLayout, lv, view1);
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout ptrFrameLayout) {

            refresh();

        }
    };
    private String shoppingCarId;

    public void updateUserProfile() {
        if (getActivity() == null) {
            return;
        }
        String token = getUser().getAccess_token();
        if (token == null || "".equals(token)) {
            Intent intent = new Intent(getAppActivity(), LoginActivity.class);
            startActivity(intent);
            return;
        }
        if (/*DataManager.getInstance().isNeedRefreshCart &&*/ getActivity() != null) {
            groupList.clear();
            adapter.notifyDataSetChanged();
            vBottom.setVisibility(View.GONE);
            refresh();
            DataManager.getInstance().isNeedRefreshCart = false;
        }
    }

    public void refresh() {

        if (getActivity() != null)
        requestCartList();
    }

    public Timer timer;
    boolean isTimerAlive;
    TimerTask task ;
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler(){

        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    if(getAppActivity()!=null)
                        adapter.notifyDataSetChanged();
                    break;
            }
            super.handleMessage(msg);
        }

    };
    @Override
    public void onPause() {
        super.onPause();
        timerStop();
    }

    public void timerStart() {
        timerStop();
        if(timer == null)
            timer = new Timer();

        task =  new TimerTask() {
            @Override
            public void run() {
                try {
                    if (isTimerAlive){
                        Message message = Message.obtain();
                        message.what = 1;
                        handler.sendMessage(message);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        isTimerAlive = true;

        timer.schedule(task, 0, 1000);
    }


    public void timerStop() {
        isTimerAlive = false;
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (task != null){
            task.cancel();
            task = null;
        }
    }



    @Override
    public String getBaseTag() {
        return "cartFragment";
    }

    public boolean isShowBack;
    View vBack;
    public void updateBack(boolean isShowBack){

        if (vBack == null){
            return;
        }
        if (!isShowBack) {
            vBack.setVisibility(View.GONE);
        }else {
            vBack.setVisibility(View.VISIBLE);
        }
        vBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getActivity() != null){
                    getActivity().finish();
                }
            }
        });
    }
    public void initToolbar(View v) {
        vBack = v.findViewById(R.id.baseback);
        if (!isShowBack) {
            vBack.setVisibility(View.GONE);
        }
        vBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getActivity() != null){
                    getActivity().finish();
                }
            }
        });
        TextView tvTitle = (TextView) v.findViewById(R.id.toolbar_title);
        tvRight = (TextView) v.findViewById(R.id.rightbtn);
        tvRight.setText(R.string.edit);
        tvRight.setOnClickListener(this);
        tvRight.setVisibility(View.VISIBLE);

        tvOffer = (TextView) v.findViewById(R.id.rightbtn2);
        tvOffer.setOnClickListener(this);
        vLine = v.findViewById(R.id.rightbtn_line);
        vLine.setVisibility(View.VISIBLE);
        tvOffer.setVisibility(View.VISIBLE);
        tvTitle.setText(R.string.cart_page);
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        return inflater.inflate(R.layout.fragment_cart,
                container, false);
    }



    @Override
    public void onStart() {
        super.onStart();
    }

    public void onRefreshCart() {
        updateUserProfile();
    }

    TextView tvClearDisable;
    View rlClearDisable;
    private View getCartFootView(View v){
        View vFoot = LayoutInflater.from(getActivity()).inflate(R.layout.cart_clear_foot_view, null, false);
        tvClearDisable = (TextView) vFoot.findViewById(R.id.tv_clear_disable);
        rlClearDisable =  vFoot.findViewById(R.id.rl_clear_disable);

        tvClearDisable.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openClearDialog();
            }
        });
        return vFoot;
    }



    private void updateClearStatus(boolean isShow){
        if (isShow && tvClearDisable != null){
            tvClearDisable.setVisibility(View.VISIBLE);
            rlClearDisable.setVisibility(View.VISIBLE);
        }else if (!isShow && tvClearDisable != null){
            tvClearDisable.setVisibility(View.GONE);
            rlClearDisable.setVisibility(View.GONE);
        }
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initToolbar(view);

        vBottom = view.findViewById(R.id.ly_bottom);
        vBottom.setVisibility(View.GONE);
        ivCheck = (ImageView) view.findViewById(R.id.iv_box);

        tvAll = (TextView) view.findViewById(R.id.tv_all);
        tvTotal = (TextView) view.findViewById(R.id.tv_total);
        tvTotalName = (TextView) view.findViewById(R.id.tv_total_name);
        tvOtherPrice = (TextView) view.findViewById(R.id.tv_other_price);
        tvBtn = (TextView) view.findViewById(R.id.tv_btn);

        tvOtherPrice.setVisibility(View.GONE);
        tvBtn.setOnClickListener(this);

        ivCheck.setOnClickListener(this);
        tvAll.setOnClickListener(this);

        msView = (MultiStateView) view.findViewById(R.id.ms_view);
        msView.setViewForState(R.layout.loading_view, MultiStateView.VIEW_STATE_LOADING);
        msView.setViewForState(R.layout.empty_cart_goods, MultiStateView.VIEW_STATE_EMPTY);
        msView.setViewForState(R.layout.error_view, MultiStateView.VIEW_STATE_ERROR);
        View emptyView = msView.getmEmptyView();
        if (emptyView != null) {

            emptyView.findViewById(R.id.tv_btn_cart).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    intoHomePage();
                }
            });
        }
        msView.setOnErrorClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                refresh();
            }
        });
        frameLayout = (PtrMdFrameLayout) view.findViewById(R.id.ptr);
        lv = (ExpandableListView) view.findViewById(R.id.lv);

        lv.addFooterView(getCartFootView(view));
        frameLayout.setPtrHandler(ptrHandler);
        adapter = new CartExpandListAdapter(getContext(), lv, groupList);
        adapter.setFreshItemListener(new CartExpandListAdapter.FreshItemListener() {
            @Override
            public void freshItem(int type, int position, CartGood goods, View v) {
                requestFreshItem(goods);
            }
        });
        adapter.setDeleteOne(new CartExpandListAdapter.DeleteOne() {
            @Override
            public void deleteOne(int groupPosition, int childPosition) {
                openDeleteDialog(groupPosition,childPosition);
            }
        });
        lv.setAdapter(adapter);
        adapter.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView expandableListView, View view, int i, int i1, long l) {


                if (i < groupList.size()) {
                    CartGoods cartGoods = groupList.get(i);
                    if(cartGoods.isDisabled()){
                        return true;
                    }
                    List<CartGood> result = cartGoods.getResult();
                    if (result != null && result.size() > i1) {
                        CartGood cartGood = result.get(i1);
                        if (cartGood.getWholeSalesType() == 1) {
//                            String id = cartGood.getProductId();
                            String id = cartGood.getSpecId();
                            Intent intent = new Intent(getContext(), DetailGoodsActivity.class);
                            intent.putExtra("id", id + "");
                            intent.putExtra("storeId",cartGood.getStoreId());
                            intent.putExtra("promotionItemId", cartGood.getPromotionItemId());
                            intent.putExtra("serviceStoreId",Integer.valueOf(cartGood.getStoreId()));
                            startActivity(intent);
                        } else {
//                            String id = cartGood.getProductId();
                            String id = cartGood.getSpecId();
                            Intent intent = new Intent(getContext(), DetailGoodsActivity.class);
                            intent.putExtra("id", id + "");
                            intent.putExtra("storeId",cartGood.getStoreId());
                            intent.putExtra("promotionItemId", cartGood.getPromotionItemId());
                            intent.putExtra("serviceStoreId",Integer.valueOf(cartGood.getStoreId()));
                            startActivity(intent);
                        }
                    }
                }
                return true;
            }
        });

        adapter.setOnTextChangeListener(new CartExpandListAdapter.OnTextChangeListener() {

            @Override
            public void onTextChange(int groupPosition, int childPosition, double lastCnt, CartGood cartGood) {
                openDialog(groupPosition, childPosition, cartGood);

            }
        });

        adapter.setOnMsgAddListener(new CartExpandListAdapter.OnMsgAddListener() {
            @Override
            public void onMsgAdd(int position, CartGood goods) {
                msgPosition = position;
                requestFastMerTagList(goods);
                //openMsgDialog(position,goods);
            }
        });

        adapter.setOnChangeListener(new CartExpandListAdapter.OnTextChangeListener() {//加 减购物车
            @Override
            public void onTextChange(int groupPosition, int childPosition, double lastCnt, CartGood cartGood) {
                calTotalPrice(adapter.calAllCheckedStatus());
//                cntCart(cartGood.getId() + "", cartGood.getCount(), lastCnt);
                updateCartCnt(lastCnt,cartGood);
                adapter.notifyDataSetChanged();

                //刷新购物车列表
//                refresh();
            }
        });

        adapter.setOnCheckChangeListener(new CartExpandListAdapter.OnCheckChangeListener() {
            @Override
            public void onCheckChange(boolean isCheck, int groupPosition, int childPosition) {

                tvAll.setTag(isCheck);
                ivCheck.setTag(isCheck);
                adapter.checkBoxState(isCheck, ivCheck);
                Pair<Integer, Double> pair = adapter.calAllCheckedStatus();
                calTotalPrice(pair);

                List<Map<String, Object>> selectedStatus = adapter.getSelectedStatus(groupPosition, childPosition);
                if (selectedStatus != null && selectedStatus.size() > 0 && !adapter.isEdit()) {
                    saveSelected(selectedStatus);
                }
            }
        });

        adapter.setOnNotifyDataSetChangedListener(new CartExpandListAdapter.OnNotifyDataSetChangedListener() {
            @Override
            public void OnNotifyDataSetChangedListener(int size) {
                boolean b = adapter.checkAllStatus();
                tvAll.setTag(b);
                ivCheck.setTag(b);
                adapter.checkBoxState(b, ivCheck);

                calTotalPrice(adapter.calAllCheckedStatus());
            }
        });

        adapter.setOnChildLongClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView expandableListView, View view, int i, int i1, long l) {

                if (i < groupList.size()) {

                    CartGoods cartGoods = groupList.get(i);
                    if (cartGoods != null) {
                        List<CartGood> result = cartGoods.getResult();
                        if (result != null && i1 < result.size()) {
                            CartGood cartGood = result.get(i1);
                            if (cartGood != null) {

                                String id = cartGood.getId();
                                List<String> ids = new ArrayList<String>();
                                ids.add(id);
                                openDeleteDialog(ids);
                                return true;
                            }
                        }
                    }
                }

                return false;
            }
        });

        //结算
        adapter.setOnCountListener(new CartExpandListAdapter.OnCountListener() {
            @Override
            public void onCountListener(CartGoods cartGoods, boolean isUnable) {

                if (isUnable){
                    T.toast("请选择要结算的商品");
                    return;
                }
                if (cartGoods == null){
                    return;
                }
                List<CartGoods> list = new ArrayList<>();
                list.add(cartGoods);
                DataManager.getInstance().setCartGoods(list);


                intoCartOrderPage();
            }
        });

        init();

    }
    private void intoHomePage() {
        Intent intent = new Intent(getContext(), HomeActivity.class);

        intent.putExtra("home_tab_index", 0);
        startActivity(intent);

    }

    private void intoCartOrderPage(){
        Intent intent = new Intent();
        //intent.setClass(getContext(), CartOrderActivity.class);
        intent.setClass(getContext(), CartOrderNewActivity.class);
        startActivityForResult(intent,0x002);//留言
    }

    CustomDialog.Builder builder;

    public void openDeleteDialog(final int groupPositon, final int childPosition) {// TODO: 2017/11/10 数量减到0也是弹出删除窗口

        if (builder == null) {
            builder = new CustomDialog.Builder(getContext());
        }

        if(groupList != null && groupList.size() > 0){

            String msg = "确认删除商品？";
            final List<String> ids = new ArrayList<String>();

            ids.add(groupList.get(groupPositon).getResult().get(childPosition).getId());

            builder.setTitleVisible(false).setMessage(msg)//设置显示的内容
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加确定按钮
                        @Override
                        public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                            deleteCart(ids);
                            dialog.dismiss();
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加返回按钮
                @Override
                public void onClick(DialogInterface dialog, int which) {//响应事件

                    dialog.dismiss();
                }

            });//在按键响应事件中显示此对话框

            builder.create().show();
        }
    }


    public void openDeleteDialog(final List<String> ids) {// TODO: 2017/11/10 数量减到0也是弹出删除窗口

        if (builder == null) {
            builder = new CustomDialog.Builder(getContext());
        }

        if(ids != null && ids.size() > 0){

            int size = ids.size();
            String msg = "确认删除商品？";
            if (size == 1){
                msg = "确认删除商品？";
            }else {
//                msg = "确认要删除这"+size+"种商品吗？";
            }

            builder.setTitleVisible(false).setMessage(msg)//设置显示的内容
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加确定按钮
                        @Override
                        public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                            deleteCart(ids);
                            dialog.dismiss();
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加返回按钮
                @Override
                public void onClick(DialogInterface dialog, int which) {//响应事件

                    dialog.dismiss();
                }

            });//在按键响应事件中显示此对话框

            builder.create().show();
        }
    }
    CustomDialog.Builder builderClear;

    public void openClearDialog() {

        if (builderClear == null) {
            builderClear = new CustomDialog.Builder(getContext());
        }


            String msg = "确认清空失效商品？";

            builderClear.setTitleVisible(false).setMessage(msg)//设置显示的内容
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加确定按钮
                        @Override
                        public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                           clearDisable();
                            dialog.dismiss();
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加返回按钮
                @Override
                public void onClick(DialogInterface dialog, int which) {//响应事件

                    dialog.dismiss();
                }

            });//在按键响应事件中显示此对话框

            builderClear.create().show();

    }


    public void updateBtnStatus() {
        if (getActivity() != null && tvBtn != null) {
            adapter.setEdit(false);
            tvRight.setText(R.string.edit);
//            tvTotal.setVisibility(View.VISIBLE);
            tvTotal.setVisibility(View.GONE);
//            tvTotalName.setVisibility(View.VISIBLE);
            tvTotalName.setVisibility(View.GONE);
            tvOtherPrice.setVisibility(View.GONE);
            tvBtn.setBackgroundResource(R.drawable.btn_cart);
            adapter.notifyDataSetChanged();
        }
    }


    //快捷"+"、"-"
    public void openDialog(int groupPosition, int childPosition, final CartGood cartGood) {
        if (getActivity() == null) {
            return;
        }
        final Dialog dialog = new Dialog(getContext(), R.style.no_title_dialog);

        dialog.setContentView(R.layout.dialog_cart_add);
        ImageView ivAdd = (ImageView) dialog.findViewById(R.id.iv_add);
        ImageView ivRemove = (ImageView) dialog.findViewById(R.id.iv_remove);

        final EditText ed = (EditText) dialog.findViewById(R.id.ed_price);

        ed.setText(FormatUtil.subZeroAndDot(cartGood.getCount() + ""));
        ed.setSelection(ed.length());
        CashierInputFilter cashierInputFilter = new CashierInputFilter();
        cashierInputFilter.MAX_VALUE = 999999;
        ed.setFilters(new InputFilter[]{cashierInputFilter});

        ed.setFocusable(true);

        ivAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String s = ed.getText().toString();
                double min = cartGood.getMinPlaceOrderValue();
                double incr =  cartGood.getIncr();
                double cnt = min;
                Log.d("cnt", "s:" + s);
                if (s.length() > 0) {
                    cnt = Double.valueOf(s);
                }
                double amount = cnt;

                if (cartGood.getWholeSalesType() == 1) {

                    if (FormatUtil.remainderZero(amount,cartGood.getMaxPlaceOrderValue())>0){
                        amount = cartGood.getMaxPlaceOrderValue();
                    }

//                    if (amount > cartGood.getMaxPlaceOrderValue()) {
//                        amount = cartGood.getMaxPlaceOrderValue();
//                    }
//                    amount += incr;
                    amount = FormatUtil.countAdd(amount,incr);
//                    if (amount > cartGood.getMaxPlaceOrderValue()) {
//                        amount = cartGood.getMaxPlaceOrderValue();
//                    }
                    if (FormatUtil.remainderZero(amount,cartGood.getMaxPlaceOrderValue())>0){
                        amount = cartGood.getMaxPlaceOrderValue();
                    }

                } else {
                   amount = FormatUtil.countAdd(amount,incr);
                }
//                cartGood.setProductCount(amount);
                ed.setText(FormatUtil.subZeroAndDot(amount + ""));
            }
        });
        ivRemove.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String s = ed.getText().toString();
                double min = cartGood.getMinPlaceOrderValue();
                double incr =  cartGood.getIncr();
                double cnt = min;
                Log.d("cnt", "s:" + s);
                if (s.length() > 0) {
                    cnt = Double.valueOf(s);
                }
                double amount = cnt;
//                if (cartGood.getWholeSalesType() == 1) {
                if (amount < cartGood.getMinPlaceOrderValue()) {
                    amount = cartGood.getMinPlaceOrderValue();
                }

                amount= FormatUtil.countSubtract(amount,incr);
                if (amount < cartGood.getMinPlaceOrderValue()) {
                    amount = cartGood.getMinPlaceOrderValue();
                }
//                } else {
//                    amount--;
//                    if (amount < 1) {
//                        amount = 1;
//                    }
//                }
//                cartGood.setProductCount(amount);
                ed.setText(FormatUtil.subZeroAndDot(amount + ""));
            }
        });
        dialog.findViewById(R.id.negativeButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm.isActive()) {
                    imm.hideSoftInputFromWindow(ed.getApplicationWindowToken(), 0);
                }
                dialog.dismiss();
            }
        });

        dialog.findViewById(R.id.positiveButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                double productCount = cartGood.getCount();
                String s = ed.getText().toString();
                double min = cartGood.getMinPlaceOrderValue();
                double incr =  cartGood.getIncr();
                double cnt = min;
                Log.d("cnt", "s:" + s);
                if (s.length() > 0) {
                    cnt = Double.valueOf(s);
                }
                if (cnt < 0.01 || cnt < min) {
                    T.toast("不能少于"+FormatUtil.subZeroAndDot(min+""));
                    cnt = FormatUtil.countFormat(cnt,incr,min);
                    ed.setText(FormatUtil.subZeroAndDot(cnt + ""));
                    ed.setSelection(ed.getText().length());
                    return;
                }
                if (cartGood.getWholeSalesType() == 1) {
                    Log.d("cnt", "cnt:" + cnt);
                    Log.d("cnt", "cnt2:" + cartGood.getMinPlaceOrderValue());
                    Log.d("cnt", "cnt3:" + cartGood.getMaxPlaceOrderValue());

                    if (cnt > cartGood.getMaxPlaceOrderValue()) {
                        T.toast("超过库存");
                        cnt = FormatUtil.countFormat(cartGood.getMaxPlaceOrderValue(),incr,min);

                        ed.setText(FormatUtil.subZeroAndDot(cnt + ""));
                        ed.setSelection(ed.getText().length());
                        return;
                    }
                }
                incr = incr < 0.01 ? min : incr;

                if (FormatUtil.isRemainder(cnt,incr,min)) {
                    cnt = FormatUtil.countFormat(cnt,incr,min);
                    Log.e("cnt:","cnt:"+FormatUtil.subZeroAndDot(cnt + ""));
                    ed.setText(FormatUtil.subZeroAndDot(cnt + ""));
                    ed.setSelection(ed.getText().length());
                    return;
                }

                cartGood.setProductCount(cnt);
//                cntCart(cartGood.getId() + "", cnt, productCount);
                Log.e("productCnt","productCnt:"+productCount);
                updateCartCnt(cartGood.getProductCount(),cartGood);
                adapter.notifyDataSetChanged();
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm.isActive()) {
                    imm.hideSoftInputFromWindow(ed.getApplicationWindowToken(), 0);
                }
                dialog.dismiss();
            }
        });

       dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm.isActive()) {
                    imm.hideSoftInputFromWindow(ed.getApplicationWindowToken(), 0);
                }
            }
        });

        dialog.show();
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                InputMethodManager inputManager =
                        (InputMethodManager) ed.getContext().getSystemService(
                                Context.INPUT_METHOD_SERVICE);
                inputManager.showSoftInput(ed, 0);
            }
        }, 200);

    }

    private void calTotalPrice(Pair<Integer, Double> pair) {
        String s = tvRight.getText().toString();
        if (getString(R.string.finish).equals(s)) {
            tvBtn.setText(getString(R.string.delete_d, pair.first));
        } else {
            tvBtn.setText(getString(R.string.merge_d, pair.first));
        }

        if (pair.first < 1) {
            tvBtn.setEnabled(false);
        } else {
            tvBtn.setEnabled(true);

        }
        tvTotal.setText(getString(R.string.total_price, pair.second));
    }

    boolean showTips;
    private void init() {
        showTips = true;
        onRefreshCart();
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.rightbtn2:
                Intent more_activity = new Intent(v.getContext(),
                        OfferListActivity.class);
                v.getContext().startActivity(more_activity);
                break;
            case R.id.rightbtn:
                String s = tvRight.getText().toString();
                //从非编辑状态切换到编辑状态
                if (getString(R.string.edit).equals(s)) {
                    adapter.setEdit(true);
                    tvRight.setText(R.string.finish);
                    tvTotal.setVisibility(View.INVISIBLE);
//                    tvTotalName.setVisibility(View.INVISIBLE);
//                    tvOtherPrice.setVisibility(View.INVISIBLE);
                    tvOtherPrice.setVisibility(View.GONE);
                    tvTotalName.setVisibility(View.GONE);
                    tvTotal.setVisibility(View.GONE);
                    vBottom.setVisibility(View.VISIBLE);

                    adapter.editState();
                    tvBtn.setBackgroundResource(R.drawable.btn_cart_del);
                    adapter.notifyDataSetChanged();
                } else {
                    adapter.setEdit(false);
                    tvRight.setText(R.string.edit);
                    vBottom.setVisibility(View.GONE);
//                    tvTotal.setVisibility(View.VISIBLE);
                    tvTotal.setVisibility(View.GONE);
//                    tvTotalName.setVisibility(View.VISIBLE);
                    tvTotalName.setVisibility(View.GONE);
                    tvOtherPrice.setVisibility(View.GONE);
                    adapter.releaseStatus();
                    tvBtn.setBackgroundResource(R.drawable.btn_cart);
                    adapter.notifyDataSetChanged();
                }
                calTotalPrice(adapter.calAllCheckedStatus());
                break;
            case R.id.tv_btn:
                String s0 = tvRight.getText().toString();
                //结算状态
                if (getString(R.string.edit).equals(s0)) {
                    //如果结算商品个数为0
                    Integer first = adapter.calAllCheckedStatus().first;
                    if (first != null && first > 0) {

                        if (first > 300){
                            T.toast("每次可结算300个商品，请减少商品数量");
                            return;
                        }
                        adapter.notifyDataSetChanged();

                        intoCartOrderPage();
                    }
                } else {//删除状态
                    //如果结算商品个数为0无法编辑
                    List<String> allCheckedStatus = adapter.getAllCheckedStatus();
                    if (allCheckedStatus != null && allCheckedStatus.size() > 0) {

                        openDeleteDialog(allCheckedStatus);
                    }
                }


                break;
            case R.id.iv_box:
            case R.id.tv_all:
                Object tag = ivCheck.getTag();
                if (tag instanceof Boolean) {
                    boolean b = (boolean) tag;
                    tvAll.setTag(!b);
                    ivCheck.setTag(!b);
                    adapter.checkBoxState(!b, ivCheck);
                    adapter.checkAllStatus(!b);
                    List<Map<String, Object>> selectedStatus = adapter.getSelectedStatus(-1, -1);
                    if (selectedStatus != null && selectedStatus.size() > 0 && !adapter.isEdit()) {
                        saveSelected(selectedStatus);
                    }
                }
                break;

        }
    }


    public void emptyView() {


        if (groupList.size() > 0) {
            CartGoods cartGoods = groupList.get(0);
            if (cartGoods != null && cartGoods.isDisabled() && (cartGoods.getResult() == null || cartGoods.getResult().size() == 0)) {
                msView.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                vBottom.setVisibility(View.GONE);
                tvRight.setVisibility(View.GONE);
                vLine.setVisibility(View.GONE);
                tvOffer.setVisibility(View.GONE);
            } else {
                showTips();
                msView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
//                vBottom.setVisibility(View.VISIBLE);
                tvRight.setVisibility(View.VISIBLE);
                vLine.setVisibility(View.VISIBLE);
                tvOffer.setVisibility(View.VISIBLE);
                vBottom.setVisibility(View.GONE);
            }
        } else {
            msView.setViewState(MultiStateView.VIEW_STATE_EMPTY);
            vBottom.setVisibility(View.GONE);
            tvRight.setVisibility(View.GONE);
            vLine.setVisibility(View.GONE);
            tvOffer.setVisibility(View.GONE);
        }
    }


    OnRequestListener<ContentEntity<CartGoods>> onCartRequestListener = new OnRequestListener<ContentEntity<CartGoods>>() {
        @Override
        public ContentEntity<CartGoods> jsonToObj(String s) {
            return new Gson().fromJson(s, new TypeToken<ContentEntity<CartGoods>>() {
            }.getType());
        }

        @Override
        public void onFail(int i, Object o, Object o1) {
            frameLayout.refreshComplete();
            if (groupList.size() == 0) {
                msView.setViewState(MultiStateView.VIEW_STATE_ERROR);
                vBottom.setVisibility(View.GONE);
                tvRight.setVisibility(View.GONE);
                vLine.setVisibility(View.GONE);
                tvOffer.setVisibility(View.GONE);
            }
        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {
            frameLayout.refreshComplete();

            if (groupList.size() == 0) {
                msView.setViewState(MultiStateView.VIEW_STATE_ERROR);
                vBottom.setVisibility(View.GONE);
                tvRight.setVisibility(View.GONE);
                vLine.setVisibility(View.GONE);
                tvOffer.setVisibility(View.GONE);
            }
        }

        @Override
        public void onStart(Object o) {
//            if (!frameLayout.isRefreshing())
//                msView.setViewState(MultiStateView.VIEW_STATE_LOADING);
            if (groupList.size() == 0) {
                vBottom.setVisibility(View.GONE);
                tvRight.setVisibility(View.GONE);
                vLine.setVisibility(View.GONE);
                tvOffer.setVisibility(View.GONE);
            }
        }

        @Override
        public void onResponse(ResponseEntity<ContentEntity<CartGoods>> responseEntity, Object o) {
            frameLayout.refreshComplete();
            ContentEntity<CartGoods> responseElement = responseEntity.getResponseElement();
            Log.d("listShoppingCar",(responseElement != null && getActivity() != null)+"");
            if (responseElement != null && getActivity() != null) {
                List<CartGoods> content = responseElement.getContent();
                if (content != null) {
                    groupList.clear();
                    for (int i = 0; i < content.size(); i++) {
                        CartGoods cartGoods = content.get(i);
                        List<CartGood> result = cartGoods.getResult();
                        if (result != null && result.size() > 0) {

                            groupList.add(cartGoods);
                            if (!cartGoods.isDisabled()){
                                updateClearStatus(false);
                            }else {
                                updateClearStatus(true);
                            }
                        }
                    }

                    updateBtnStatus();
                    adapter.notifyDataSetChanged();
                    adapter.checkStatus();
//                    DataManager.getInstance().setCartCntStatus(size);
                    timerStart();

                    DataManager.getInstance().updateCartCnt();
                }

            }

            emptyView();

        }
    };

    public void requestCartList() {

        if (ApplicationHelper.getInstance().getUser().getAccess_token() == null || "".equals(ApplicationHelper.getInstance().getUser().getAccess_token())) {
            return;
        }
        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_order_cart_list);
        re.putParameter("cityId", ApplicationHelper.getInstance().getCity().getCityId());

        re.putParameter("accountId", ApplicationHelper.getInstance().getUser().getAccountId());
        request(re, com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_order_cart_list, onCartRequestListener);
    }


    OnRequestListener<Map<String, String>> onDeleteRequestListener = new OnRequestListener<Map<String, String>>() {
        @Override
        public Map<String, String> jsonToObj(String s) {
            return new Gson().fromJson(s, new TypeToken<Map<String, String>>() {
            }.getType());
        }

        @Override
        public void onFail(int i, Object o, Object o1) {

        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {

        }

        @Override
        public void onStart(Object o) {

        }

        @Override
        public void onResponse(ResponseEntity<Map<String, String>> responseEntity, Object o) {

            Map<String, String> responseElement = responseEntity.getResponseElement();
            if (responseElement != null) {
                String shoppingCarCnt = responseElement.get("shoppingCarCnt");
                if (shoppingCarCnt != null && VerificationUtils.isNumeric(shoppingCarCnt)) {
                    refresh();
                    updateBtnStatus();
                    DataManager.getInstance().setCartCntStatus(Integer.valueOf(shoppingCarCnt));
                }
            }
        }
    };

    public void deleteCart(List<String> ids) {

        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_order_cart_delete);

        re.putParameter("cityId", ApplicationHelper.getInstance().getCity().getCityId());
        re.putParameter("ids", ids);
        re.putParameter("accountId", ApplicationHelper.getInstance().getUser().getAccountId());
        request(re, com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_order_cart_delete, onDeleteRequestListener);

    }
    OnRequestListener<Map<String, Object>> onClearRequestListener = new OnRequestListener<Map<String, Object>>() {
        @Override
        public Map<String, Object> jsonToObj(String s) {
            return new Gson().fromJson(s, new TypeToken<Map<String, Object>>() {
            }.getType());
        }

        @Override
        public void onFail(int i, Object o, Object o1) {

        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {

        }

        @Override
        public void onStart(Object o) {

        }

        @Override
        public void onResponse(ResponseEntity<Map<String, Object>> responseEntity, Object o) {

            Map<String, Object> responseElement = responseEntity.getResponseElement();
            if (responseElement != null) {
                Object success = responseElement.get("success");
                if (success != null && success instanceof Boolean) {
                    refresh();
                }
            }
        }
    };

    public void clearDisable() {

        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_order_cart_delInvalid);

        re.putParameter("cityId", ApplicationHelper.getInstance().getCity().getCityId());
        re.putParameter("accountId", ApplicationHelper.getInstance().getUser().getAccountId());
        request(re, com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_order_cart_delInvalid, onClearRequestListener);

    }
/*

    OnRequestListener<Map<String, Object>> onCntRequestListener = new OnRequestListener<Map<String, Object>>() {
        @Override
        public Map<String, Object> jsonToObj(String s) {
            return new Gson().fromJson(s, new TypeToken<Map<String, Object>>() {
            }.getType());
        }

        @Override
        public void onFail(int i, Object o, Object o1) {

        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {

        }

        @Override
        public void onStart(Object o) {

        }

        @Override
        public void onResponse(ResponseEntity<Map<String, Object>> responseEntity, Object o) {
            RequestTag tag = null;
            if (o instanceof RequestTag) {
                tag = (RequestTag) o;
            }
            Map<String, Object> responseElement = responseEntity.getResponseElement();
            if (responseElement != null) {
                Object success = responseElement.get("success");
                if (success != null && success instanceof Boolean && ((Boolean) success)) {

                }
            }
        }
    };
*/

    OnRequestListener<AddCarResponse> onCntRequestListener2 = new OnRequestListener<AddCarResponse>() {
        @Override
        public AddCarResponse jsonToObj(String s) {
            return new Gson().fromJson(s, AddCarResponse.class);
        }

        @Override
        public void onFail(int i, Object o, Object o1) {
            hideProgressDialog();
            RequestTag tag = null;

            if (o1 instanceof RequestTag) {
                tag = (RequestTag) o1;
                String arg1 = tag.arg1;
                Object arg2 = tag.arg2;
                Object o2 = tag.tag;
                if (arg1 != null && o2 != null && o2 instanceof CartGood) {
                    CartGood goods = (CartGood) o2;
//                        BigDecimal a = new BigDecimal(arg1).setScale(2, BigDecimal.ROUND_HALF_UP);
                    if (arg2 != null && arg2 instanceof Double) {
                        responseCartCnt(true, goods, -1);
                        goods.setProductCount((Double) arg2);
                        adapter.notifyDataSetChanged();
                        T.toast(" 添加购物车失败");
                    }
                }
            }
        }

        @Override
        public void onResponseError(int i, Object o1, Object o) {
            hideProgressDialog();
            RequestTag tag = null;

            if (i / 100 == 4){
                T.toast(o1+"");
            }
            if (o instanceof RequestTag) {
                tag = (RequestTag) o;
                String arg1 = tag.arg1;
                Object arg2 = tag.arg2;
                Object o2 = tag.tag;
                if (arg1 != null && o2 != null && o2 instanceof CartGood) {
                    CartGood goods = (CartGood) o2;
//                        BigDecimal a = new BigDecimal(arg1).setScale(2, BigDecimal.ROUND_HALF_UP);

                    if (arg2 != null && arg2 instanceof Double) {
                        responseCartCnt(true, goods, -1);
                        goods.setProductCount((Double) arg2);
                        adapter.notifyDataSetChanged();

                        if (i / 100 != 4){
                            T.toast("添加购物车失败");
                        }
                    }
                }
            }
        }

        @Override
        public void onStart(Object o) {

            //showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<AddCarResponse> responseEntity, Object o) {

            hideProgressDialog();
            AddCarResponse responseElement = responseEntity.getResponseElement();
            if (responseElement != null) {

                DataManager.getInstance().oftenListReFresh = true;

                RequestTag tag = null;
                if (o instanceof RequestTag) {
                    tag = (RequestTag) o;
                    String arg1 = tag.arg1;
                    Object o2 = tag.tag;
                    if (arg1 != null && o2 != null && o2 instanceof CartGood) {
//                        CartGood goods = (CartGood) o2;
////                        BigDecimal a = new BigDecimal(arg1).setScale(2, BigDecimal.ROUND_HALF_UP);
//                        goods.setCount(responseElement.getProductCnt());
//                        goods.setShoppingCarId(responseElement.getShoppingCarId());
                        // TODO: 2018/4/20
                        if(responseElement.getOfferMsg()!=null&&!"".equals(responseElement.getOfferMsg()))
                            T.toast(""+responseElement.getOfferMsg());
/*                        if(responseElement.getProductUnitPrice()!=null&&0!=responseElement.getProductUnitPrice());
                            ((CartGood) o2).setProductUnitPrice(responseElement.getProductUnitPrice());*/
                        responseCartCnt(false, (CartGood)o2, responseElement.getProductCnt());
                        DataManager.getInstance().setCartCntStatus(responseElement.getshoppingCarCnt());
//                        adapter.notifyDataSetChanged();
                        refresh();
                    }
                }


            }
        }
    };

/*    public void cntCart(String id, double productCount, double lastCnt) {

        RequestEntityMap re = new RequestEntityMap();
        re.setCmd("appOrder/updateShoppingCarProductCount");

        re.putParameter("id", id);
        re.putParameter("productCount", productCount);
        re.putParameter("accountId", ApplicationHelper.getInstance().getUser().getAccountId());

        RequestTag tag = new RequestTag();
        tag.tag = "appOrder/updateShoppingCarProductCount";
        tag.arg1 = lastCnt +"";
        request(re, tag, onCntRequestListener);

    }*/

    public void updateCartCnt(double lastCnt,CartGood goods) {

        if (getActivity() == null) {
            return;
        }
        //goods.setProductCount(lastCnt);
        adapter.notifyDataSetChanged();
        if (cartHelper.checkIsCartRequesting(goods)) {
            return;
        }
        double count = goods.getCount();
//        if (goods != null) {
//            goods.setProductCount(productCount);
//
//        }

        Log.e("productCnt","lastCnt:"+lastCnt);
        Log.e("productCnt","count:"+count);
        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_order_cart_add);


//        private Long promotionItemId;//促销场次ID
//        private Long promotionId;//促销ID
//        private Integer promotionType;//促销场次ID
/*
        re.putParameter("promotionItemId", goods.getPromotionItemId());

        re.putParameter("shoppingCarId", goods.getShoppingCarId());
        re.putParameter("productUnitPrice", goods.getProductUnitPrice());
        re.putParameter("productId", goods.getSpecId());
        re.putParameter("salesType", goods.getSalesType());
        re.putParameter("versionId", goods.getVersionId());
        re.putParameter("cityId", ApplicationHelper.getInstance().getCity().getCityId());
        re.putParameter("productCount", count);
        re.putParameter("accountId", ApplicationHelper.getInstance().getUser().getAccountId());
*/

        re.putParameter("specId", goods.getSpecId());
        re.putParameter("specPromotionItemId", goods.getPromotionItemId());
        re.putParameter("count", count);
        re.putParameter("serviceStoreId",goods.getStoreId());
        RequestTag tag = new RequestTag();
        tag.tag = goods;
//        tag.tag = "appOrder/updateShoppingCarProductCount";
        tag.arg1 = count + "";
        tag.arg2 = lastCnt;
//        tag.arg2 = goods;
        if (cartHelper != null && goods !=null){
            cartHelper.updateRequest(goods.getUniqueKey());
        }
        tag.type = RequestTag.TYPE_CURRENT;
        request(re, tag, onCntRequestListener2);

    }
    CartHelper cartHelper = new CartHelper();

    public void responseCartCnt(boolean isFail, CartGood goods, double cnt) {
        if (isFail) {
            cartHelper.responseCartFail(goods);
        } else {
            cartHelper.responseCartSuccess(goods, cnt);
        }
    }
    OnRequestListener<Map<String, Object>> onUpdateSelectedRequestListener = new OnRequestListener<Map<String, Object>>() {
        @Override
        public Map<String, Object> jsonToObj(String s) {
            return new Gson().fromJson(s, new TypeToken<Map<String, Object>>() {
            }.getType());
        }

        @Override
        public void onFail(int i, Object o, Object o1) {

        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {

        }

        @Override
        public void onStart(Object o) {

        }

        @Override
        public void onResponse(ResponseEntity<Map<String, Object>> responseEntity, Object o) {

            Map<String, Object> responseElement = responseEntity.getResponseElement();
            if (responseElement != null) {
                Object success = responseElement.get("success");
                if (success != null && success instanceof Boolean && ((Boolean) success)) {

                }
            }
        }
    };

    public void saveSelected(List<Map<String, Object>> list) {


        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_order_cart_updateSelected);

        re.putParameter("list", list);

        ApplicationHelper.getInstance().requestSilent(re, com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_order_cart_updateSelected, onUpdateSelectedRequestListener);

    }



    OnRequestListener<Map<String, Object>> onSaveMsgRequestListener = new OnRequestListener<Map<String, Object>>() {
        @Override
        public Map<String, Object> jsonToObj(String s) {
            return new Gson().fromJson(s, new TypeToken<Map<String, Object>>() {
            }.getType());
        }

        @Override
        public void onFail(int i, Object o, Object o1) {

        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {
            T.toast(o + "");//arg + ",请点击重试"

        }

        @Override
        public void onStart(Object o) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<Map<String, Object>> responseEntity, Object o) {
            hideProgressDialog();
            if(msgDialog!=null)
                msgDialog.dismiss();

            Map<String, Object> responseElement = responseEntity.getResponseElement();
            if (responseElement != null) {
                Object success = responseElement.get("success");
                if (success != null && success instanceof Boolean && ((Boolean) success)) {
                    groupList.get(msgPosition/1000).getResult().get(msgPosition%1000).setMerMsg(msgNow);
                    adapter.notifyDataSetChanged();

                }
            }
        }
    };

    public void saveMsg(String msg,String goodsId) {
        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_order_cart_saveMsg);
        re.putParameter("merMsg", msg);
        re.putParameter("shoppingCarId", goodsId);
        ApplicationHelper.getInstance().requestSilent(re, com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_order_cart_saveMsg, onSaveMsgRequestListener);
    }
    int msgPosition;


    MsgDialog msgDialog;
    String msgNow;
    private void openMsgDialog(CartGood goods, List<String> list) {
        //if(msgDialog==null)
            msgDialog = new MsgDialog(getContext());
            msgDialog.setOnCommitListener(new MsgDialog.OnCommitListener() {
            @Override
            public void onCommit(String msg, String goodsId) {
                msgNow = msg;
                msgDialog.dismiss();
                saveMsg(msg,goodsId);
            }
        });
        msgDialog.show(goods.getId(),list,goods.getMerMsg());
    }

    RequestTag tag;
    public void requestFastMerTagList(CartGood cartGood) {

        if (cartGood == null) {
            return;
        }
        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_message_findByProductId);
        re.putParameter("productId", cartGood.getProductId());//todo 有数据的项太少，暂时以改项目代替

        tag = new RequestTag();
        tag.tag = com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_message_findByProductId;
        tag.arg2 = cartGood;
        tag.type = RequestTag.TYPE_CURRENT;
        request(re, tag, onRequestFastMerTagListener);
    }

    OnRequestListener<List<String>> onRequestFastMerTagListener = new OnRequestListener<List<String>>() {
        @Override
        public List<String> jsonToObj(String s) {
            return new Gson().fromJson(s, new TypeToken<List<String>>() {
            }.getType());
        }

        @Override
        public void onFail(int i, Object o, Object o1) {
            hideProgressDialog();
            if (o1 != null && o1 instanceof RequestTag) {

                RequestTag tag = (RequestTag) o1;
                Object arg2 = tag.arg2;
                if (arg2 != null && arg2 instanceof CartGood) {

                    openMsgDialog((CartGood) arg2, null);
                }
            }
        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {
            hideProgressDialog();
            if (o1 != null && o1 instanceof RequestTag) {

                RequestTag tag = (RequestTag) o1;
                Object arg2 = tag.arg2;
                if (arg2 != null && arg2 instanceof CartGood) {

                    openMsgDialog((CartGood) arg2, null);
                }
            }

        }

        @Override
        public void onStart(Object o) {
            showProgressDialog();


        }

        @Override
        public void onResponse(ResponseEntity<List<String>> responseEntity, Object o) {

            hideProgressDialog();
            List<String> responseElement = responseEntity.getResponseElement();
            if (responseElement != null && responseElement.size() > 0) {

            }
            if (o != null && o instanceof RequestTag) {

                RequestTag tag = (RequestTag) o;
                Object arg2 = tag.arg2;
                if (arg2 != null && arg2 instanceof CartGood) {

                    openMsgDialog((CartGood) arg2, responseElement);
                }
            }
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == 0x002) {
            refresh();
        }
    }


    public void requestFreshItem(final CartGood goods) {
        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_offer_findMyProductOffer);
        if(goods.getOfferProductDto()==null)
            return;
        re.putParameter("productOfferDetailsId", goods.getOfferProductDto().getProductOfferDetailsId());
        request(re, com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_offer_findMyProductOffer, new OnRequestListener<ContentEntity<OfferMyList>>() {
            @Override
            public ContentEntity<OfferMyList> jsonToObj(String responseStr) {

                return JsonUtils.fromJsonObject(responseStr, ContentEntity.class, OfferMyList.class);
            }
            @Override
            public void onFail(int i, Object o, Object o1) {
                hideProgressDialog();
            }

            @Override
            public void onResponseError(int i, Object o1, Object o) {
                hideProgressDialog();
            }

            @Override
            public void onStart(Object o) {
                //showProgressDialog();
            }

            @Override
            public void onResponse(ResponseEntity<ContentEntity<OfferMyList>> responseEntity, Object o) {
                hideProgressDialog();
                ContentEntity<OfferMyList> bean = responseEntity.getResponseElement();

                if(bean==null||bean.getResponse()==null||bean.getResponse().get(0)==null||bean.getResponse().get(0).getStatus()==1){
                    return;
                }

                goods.getOfferProductDto().setStatus(bean.getResponse().get(0).getStatus());
                //goods.getOfferProductDto().setOfferDuration(bean.getResponse().get(0).getOfferDuration());
                goods.getOfferProductDto().setOverTime(bean.getResponse().get(0).getOverTime());
                goods.getOfferProductDto().setCreateTime(bean.getResponse().get(0).getOfferTime());
                goods.getOfferProductDto().setPrice(bean.getResponse().get(0).getPrice());
                goods.getOfferProductDto().setText(bean.getResponse().get(0).getOfferStatusCopy());
                adapter.notifyDataSetChanged();
            }
        });

    }
    CarTipsDialog upGoodsTipsDialog;

    public void showTips() {
        SharedPreferences sp = getContext().getSharedPreferences("tips_show_car"/* + ApplicationHelper.getInstance().getUser().getAccountId()*/, Context.MODE_PRIVATE);
        if (0 == sp.getInt("tips_number", 0)) {
            if(showTips) {
                showTips = false;
                SharedPreferences.Editor editor = sp.edit();
                editor.putInt("tips_number", 1);
                editor.commit();
                if (upGoodsTipsDialog == null)
                    upGoodsTipsDialog = new CarTipsDialog(getContext());
                if (!upGoodsTipsDialog.isShowing())
                    upGoodsTipsDialog.show();
            }
        }
    }

}
